package com.echo.servlet.UserServlet;

import com.echo.entity.User;
import com.echo.service.UserService;
import com.echo.servlet.BaseServlet;
import com.echo.util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/profile-show")
public class ProfileShowServlet extends BaseServlet {
    private final UserService userService = new UserService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 设置编码
        setRequestEncoding(request);
        
        // 2. 校验登录状态
        if (!checkLogin(request, response)) {
            return;
        }
        
        // 3. 从session获取用户ID，然后从数据库重新查询用户信息（包含注册时间）
        User loginUser = SessionUtils.getCurrentUser(request);
        try {
            // 从数据库重新查询用户信息
            User user = userService.findUserById(loginUser.getId());
            request.setAttribute("user", user);
        } catch (Exception e) {
            // 发生异常时使用session中的用户信息作为备份
            request.setAttribute("user", loginUser);
            log("查询用户资料失败: " + e.getMessage());
        }
        
        // 4. 处理可能的成功消息
        HttpSession session = request.getSession();
        String successMsg = (String) session.getAttribute("successMsg");
        if (successMsg != null) {
            request.setAttribute("successMsg", successMsg);
            session.removeAttribute("successMsg"); // 显示后移除，避免重复显示
        }
        
        // 5. 转发到profile-show.html页面
        forward(request, response, "/profile-show.html");
    }
}